import ObjectUtil from "../../utils/ObjectUtil";
import actionInterceptorPool from "./ActionInterceptorPool";
import ActionInterceptor from "./ActionInterceptor";

class ActionInterceptorRegistrar {

    // 获取所有控制器
    interceptors() {
        return ObjectUtil.deepClone(actionInterceptorPool.interceptors)
    }

    /**
     * 添加拦截器
     * @param {InterceptorConfigType[]} interceptors 拦截器
     */
    adds(interceptors: ActionInterceptor[]) {
        if (!interceptors || interceptors.length === 0) {
            return
        }
        for (let interceptor of interceptors) {
            if (!(interceptor instanceof ActionInterceptor)) {
                throw new Error('Interceptor is not ActionInterceptor type.')
            }
            if (interceptor.name) {
                // 校验 name 重复
                if (actionInterceptorPool.interceptors.findIndex(item => item.name === interceptor.name) !== -1) {
                    throw new Error(`Interceptor name "${interceptor.name}" is repeated.`)
                }
            }

            if (interceptor.sort !== null && interceptor.sort !== undefined) {
                const lastIndex = interceptors.findLastIndex(item => item.sort && item.sort <= interceptor.sort!)
                if (lastIndex !== -1) {
                    actionInterceptorPool.interceptors.splice(lastIndex + 1, 0, interceptor)
                    continue
                } else {
                    actionInterceptorPool.interceptors.unshift(interceptor)
                    continue
                }
            }

            actionInterceptorPool.interceptors.push(interceptor)
        }
    }
}

const actionInterceptorRegistrar = new ActionInterceptorRegistrar();
export default actionInterceptorRegistrar
